package loaderlib.agent
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.net.URLLoaderDataFormat;
	import flash.utils.ByteArray;
	
	import loaderlib.loader.LoaderManager;
	
	import mx.controls.Image;
	import mx.managers.SystemManagerGlobals;
	import mx.utils.LoaderUtil;

	public class ImageAgent extends Image implements IRequester
	{
		public var tag:String="default";
		
		private var _url:String;
		private var _dataFormat:String;
		
		public function ImageAgent()
		{
			super();
		}
		
		override public function load(url:Object=null):void
		{
			var cls:Class;
			var urlString:String;
			if (!url || url == "")
            return;
			trace(url is ByteArray)
			if (url is String)
        	{
        		try
            	{
                	cls = Class(systemManager.getDefinitionByName(String(url)));
            	}
            	catch(e:Error)
            	{ // ignore
            	}
            	urlString = String(url);
        	}
        	else if(!(url is Class)&&!(url is ByteArray)&&!(url is DisplayObject))
        	{
        		urlString = url.toString()
        	}
        	if(cls)
        	{
        		super.load(url)
        	}
        	else if(urlString)
        	{
        		if (!(urlString.indexOf(":") > -1 || urlString.indexOf("/") == 0 || urlString.indexOf("\\") == 0))
            	{
                	var rootURL:String;
                	if (SystemManagerGlobals.bootstrapLoaderInfoURL != null && SystemManagerGlobals.bootstrapLoaderInfoURL != "")
                    	rootURL = SystemManagerGlobals.bootstrapLoaderInfoURL;
                	else if (root)
                    	rootURL = LoaderUtil.normalizeURL(root.loaderInfo);
                	else if (systemManager)
                    	rootURL = LoaderUtil.normalizeURL(DisplayObject(systemManager).loaderInfo);

	                if (rootURL)
    	            {
        	            var lastIndex:int = Math.max(rootURL.lastIndexOf("\\"), rootURL.lastIndexOf("/"));
            	        if (lastIndex != -1)
                	        urlString = rootURL.substr(0, lastIndex + 1) + urlString;
                	}
         	   }
         		this._url = urlString
        		this._dataFormat = URLLoaderDataFormat.BINARY;
        		LoaderManager.DEFAULT_MANAGER.insertRequester(this)
        	}
        	else
        	{
        		super.load(url)
        	}
    	
		}
		
		public function get url():String
		{
			return this._url;
		}
		
		public function get dataFormat():String
		{
			return this._dataFormat;
		}
		
		public function getData(data:*):Boolean
		{
			this.source = data
			return true;
		}
		
		public function get loaderTag():String
		{
			return this.tag;
		}
		
	}
}